#
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from apps.user.models import User
from utils.password_encode import get_md5


class UserSerializer(serializers.ModelSerializer):
    # 指定字段,唯一性验证email
    email = serializers.EmailField(
        required=True,
        allow_blank=True,
        validators=[UniqueValidator(queryset=User.objects.all(), message='邮箱已存在')]
    )
    password = serializers.CharField(write_only=True)

    def create(self, validated_data):
        # 将用户的密码转换为MD5哈希
        validated_data['password'] = get_md5(validated_data['password'])
        # 使用处理后的数据创建一个新的用户实例,并返回
        # result =User.objects.create(**validated_data)
        return User.objects.create(**validated_data)

    class Meta:
        model = User
        fields = "__all__"
